// pages/goods-add/goods-add.js
import http from '../../utils/http.js'
const { addGoods, getManufacturerList } = require('../../utils/apiConfig')

Page({
  data: {
    manufacturers: [],
    selectedManufacturer: null,
    formData: {
      goods_name: '',
      manufacturer_id: '',
      cost_price: '',
      sales_price: ''
    }
  },

  onLoad() {
    this.loadManufacturers()
  },

  // 加载厂家数据
  async loadManufacturers() {
    try {
      const res = await http.request({
        url: getManufacturerList,
        method: 'GET'
      })
      this.setData({
        manufacturers: res.data.data.map(item => ({
          id: item.id,
          manufacturer_name: item.manufacturer_name
        }))
      })
    } catch (error) {
      wx.showToast({
        title: '加载厂家列表失败',
        icon: 'none'
      })
    }
  },

  // 厂家选择器变更
  bindManufacturerChange(e) {
    const index = e.detail.value
    this.setData({
      selectedManufacturer: this.data.manufacturers[index],
      'formData.manufacturer_id': this.data.manufacturers[index].id
    })
  },

  // 表单提交
  async formSubmit(e) {
    const formData = e.detail.value
    if (!formData.manufacturer_id) {
      wx.showToast({ title: '请选择厂家', icon: 'none' })
      return
    }

    wx.request({
      url: app.globalData.apiUrl + '/goods',
      method: 'POST',
      data: {
        ...formData,
        manufacturer_id: this.data.selectedManufacturer.id
      },
      success: (res) => {
        if (res.statusCode === 201) {
          // 获取页面栈并刷新前页
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2]
          if (prevPage && prevPage.route === 'pages/goods/goods') {
            prevPage.loadGoodsList()
          }
          wx.navigateBack()
        } else {
          wx.showToast({ title: '提交失败', icon: 'none' })
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' })
      }
    })
  },

  // 返回按钮
  navigateBack() {
    wx.navigateBack()
  }
})